#!/usr/bin/env python
# -*- coding:utf-8 -*-

from controller.userWordTimesController import UserWordTimesController

import datetime
import math

from flask import current_app, jsonify
from sqlalchemy import or_,and_
from werkzeug.security import generate_password_hash, check_password_hash

from app import db
from models.word import Word
from models.user_word_times import UserWordTimes
from utils import commons
from utils.generate_id import GenerateID
from utils.loggings import loggings
from utils.response_code import RET, error_map_EN
from utils.rsa_encryption_decryption import RSAEncryptionDecryption

class UserWordTimesService(UserWordTimesController):

    @classmethod
    def get_user_learning_records(cls, user_id):
        """
        获取指定用户的单词学习记录，包含单词的具体内容和学习次数
        :param user_id: 用户ID
        :return: 学习记录列表
        """
        try:
            # 查询数据库并返回结果
            query = db.session.query(
                UserWordTimes,
                Word
            ).join(
                Word, UserWordTimes.word_id == Word.word_id
            ).filter(
                and_(UserWordTimes.user_id == user_id, UserWordTimes.is_delete == 0)
            ).all()

            result = []
            record = [
                {
                    'word_name': word.word_name,
                    'word_soundmark': word.word_soundmark,
                    'word_paraphrase': word.word_paraphrase,
                    'word_pronounce': word.word_pronounce,
                    'create_time': word.create_time,
                    'update_time': word.update_time,
                    'learning_times':user_word_time.learn_times
                }
                for user_word_time, word in query
            ]
            result.append(record)

            if result:
                return {'code': RET.OK, 'message': 'OK', 'data': result}
            else:
                return {'code': RET.NODATA, 'message': 'No data found', 'data': []}
        except Exception as e:
            loggings.error(1, f"Error fetching user learning records: {e}")
            return {'code': RET.DBERR, 'message': 'Database error', 'data': None}
        finally:
            db.session.close()